<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>map draw</title>
    <link rel="stylesheet" href="../js/lib/ol4.6.4/ol.css" type="text/css">
    <link rel="stylesheet" href="../css/demo.css" type="text/css">
</head>
<body>
<div id="map">
    <ul class="map-tools">
        <li id="drawTool">
            <span class="iconfont icon-duobianxing"></span>
        </li>
    </ul>
</div>
<script src="../js/lib/ol4.6.4/ol.js"></script>
<script src="../js/lib/jquery/jquery-3.3.1.min.js"></script>
<script>
    var view = new ol.View({
        zoom: 4,
        center:ol.proj.transform([110, 39],"EPSG:4326", "EPSG:3857")
    });

    var map = new ol.Map({
        controls: ol.control.defaults({
            attribution: false
        }).extend([]),
        target: "map",
        layers: [
            getTdtLayer("vec_w"),
            getTdtLayer("cva_w")
        ],
        view: view
    });

    var vectorSource = new ol.source.Vector({
        features:[]
    });
    var vector = new ol.layer.Vector({
        source: vectorSource,
        style: styleFunction
    });
    map.addLayer(vector);

    //'Point', 'LineString', 'Polygon', 'MultiPoint',
    // 'MultiLineString', 'MultiPolygon' or 'Circle'
    var draw = new ol.interaction.Draw({
        source:vectorSource,
        type:'Polygon',
        freehand: true//自由手绘
    });
    map.addInteraction(draw);
    draw.setActive(false);

    $("#drawTool").on("click", function () {
        draw.setActive(true);
    });

    var wktFormat = new ol.format.WKT();
    draw.on("drawend", function(e){
        draw.setActive(false);
        var feature = e.feature;
        console.log(wktFormat.writeGeometry(feature.getGeometry()));

        //var WKTGeo=wktFormat.writeGeometry(feature.getGeometry().transform('EPSG:3857', 'EPSG:4326'));//坐标系转换为4326
        // var data={
        //     "name":'测试1',
        //     "geom":WKTGeo+''
        // }
        // $.post('capital/insert',data,function (res){
        //     console.log(res)
        // },'json')
    });

    function styleFunction(feature) {
        var stroke = new ol.style.Stroke({
            color: 'black',
            width: 2
        });
        var fill = new ol.style.Fill({
            color: 'red'
        });
        return new ol.style.Style({
            stroke:stroke,
            fill: fill,
            image: new ol.style.Circle({
                radius: 8,
                fill: new ol.style.Fill({
                    color: "#f00"
                })
            })
        });
    }

    function getTdtLayer(lyr){
        var url = "http://t0.tianditu.com/DataServer?T="+lyr+"&X={x}&Y={y}&L={z}&tk=16c5722fed64bcdbb390cc21a5548cf9";
        var layer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                url:url
            })
        });
        return layer;
    }
</script>
</body>
</html>
